package com.sykj.seaflow.warm.core.listener;

import cn.hutool.core.util.ObjectUtil;
import com.sykj.seaflow.warm.core.handler.EmptyApproveHandler;
import com.warm.flow.core.FlowFactory;
import com.warm.flow.core.entity.Instance;
import com.warm.flow.core.entity.Node;
import com.warm.flow.core.entity.Task;
import com.warm.flow.core.entity.User;
import com.warm.flow.core.listener.Listener;
import com.warm.flow.core.listener.ListenerVariable;
import com.warm.flow.core.listener.NodePermission;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.sykj.seaflow.warm.module.nodeExt.entity.FlowNodeExt;
import com.sykj.seaflow.warm.module.nodeExt.service.FlowNodeExtService;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 全局任务创建监听拦截器
 */
@AllArgsConstructor
@Component
@Slf4j
public class GlobalCreateListener implements Listener {

    private final FlowNodeExtService nodeExtService;
    private final EmptyApproveHandler emptyApproveHandler;

    @Override
    public void notify(ListenerVariable variable) {
        log.debug("权限监听开始: {}", variable);
        // 查看源码 需要传入 NodePermission 才行， 所以这里不能直接设置task
        List<NodePermission> nodePermissionList = new ArrayList<>();
        // 获取后面的节点
        Instance instance = variable.getInstance();
        List<Task> nextTasks = variable.getNextTasks();
         // 每个监听器 都有自己的task， 不能循环所有task， 不然会多次执行
        // 先获取到当前ndoe, 查找node对应的task
        Node node = variable.getNode();
        if(nextTasks != null){
            nextTasks.stream().filter(task -> task.getNodeCode().equals(node.getNodeCode())).findFirst()
                .ifPresent(task -> {
                    String nodeCode = task.getNodeCode();
                    Long definitionId = task.getDefinitionId();
                    List<User> users = FlowFactory.userService().listByAssociatedAndTypes(task.getId());
                    if(ObjectUtil.isEmpty(users)){
                        FlowNodeExt flowNodeExt = new FlowNodeExt();
                        flowNodeExt.setDefId(definitionId);
                        flowNodeExt.setNodeCode(nodeCode);
                        FlowNodeExt nodeExt = nodeExtService.getNodeExt(flowNodeExt);
                        if(ObjectUtil.isNotNull(nodeExt)){
                            // 为空时处理
                            emptyApproveHandler.handle(nodeExt, variable, task);
                        }
                        String ext = instance.getExt();
                    }
                });
            variable.setNodePermissionList(nodePermissionList);
        }





    }

}
